<?php

namespace App\Admin\Controllers;

use App\Enums\UserStatus;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Administrator;


class AuthController extends BaseAuthController
{

    /**
     * @var string
     */
    //protected $view = 'admin.Login.getLogin';

    public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool)$request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username() => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }
        //判断登录账号是不是手机号
        if (preg_match('/^1[3456789]\d{9}$/', $credentials[$this->username()])) {
            //校验账号
            $user = User::query()
                ->where('phone', $credentials[$this->username()])
                ->where('admin_user_id', '>', 0)
                ->where('status', UserStatus::WORKING)->first();
            if (!$user) {
                return $this->validationErrorsResponse([
                    $this->username() => $this->getFailedLoginMessage(),
                ]);
            }
            $admin = Administrator::query()->where('id', $user->admin_user_id)->first();
        } else {
            //未使用手机号登录,需要判断是否是超管账号，非超管账号都不许用户名登录
            $admin = Administrator::query()->where($this->username(), '=', $credentials[$this->username()])->first();
            if (!$admin) {
                return $this->validationErrorsResponse([
                    $this->username() => $this->getFailedLoginMessage(),
                ]);
            }
            //查询此用户是否是员工，如果是员工则不允许登录
            if (User::query()->where('admin_user_id', $admin->id)->exists()) {
                return $this->validationErrorsResponse([
                    $this->username() => '请使用手机号登录',
                ]);
            }

        }
        //校验密码
        if (!Hash::check($credentials['password'], $admin->password)) {
            return $this->validationErrorsResponse([
                $this->username() => $this->getFailedLoginMessage(),
            ]);
        }
        //登录
        $this->guard()->login($admin, $remember);
        return $this->sendLoginResponse($request);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param Request $request
     * @return Response
     */
    protected function sendLoginResponse(Request $request): Response
    {
        $request->session()->regenerate();

        $path = $this->getRedirectPath();
        return $this->response()
            ->success(trans('admin.login_successful'))
            ->locationToIntended($path)
            ->locationIf(Admin::app()->getEnabledApps(), $path)
            ->send();
    }

    protected function getFailedLoginMessage()
    {
        return Lang::has('auth.failed')
            ? trans('auth.failed')
            : 'These credentials do not match our records.';
    }


    /**
     * Model-form for user setting.
     *
     * @return Form
     */
    protected function settingForm(): Form
    {
        return new Form(new Administrator(), function (Form $form) {
            $form->action(admin_url('auth/setting'));

            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });

            $form->display('username', trans('admin.username'));
            $form->text('name', trans('admin.name'))->required();
            //$form->image('avatar', trans('admin.avatar'))->autoUpload();

            $form->password('old_password', trans('admin.old_password'));

            $form->password('password', trans('admin.password'))
                ->minLength(5)
                ->maxLength(20)
                ->customFormat(function ($v) {
                    if ($v == $this->password) {
                        return;
                    }

                    return $v;
                })->help('密码必须是包含大小写字母、数字、特殊符号的8位以上');;
            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->ignore(['password_confirmation', 'old_password']);

            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $pattern = "/^(?![A-Za-z0-9]+$)(?![a-z0-9\W]+$)(?![A-Za-z\W]+$)(?![A-Z0-9\W]+$)[a-zA-Z0-9\W]{8,}$/";
                    if (!preg_match($pattern, $form->password)) {
                        return $form->response()->error('密码格式不正确');
                    }
                    $form->password = bcrypt($form->password);
                }

                if (!$form->password) {
                    $form->deleteInput('password');
                }
                $form->name = $form->name;
            });

            $form->saved(function (Form $form) {
                return $form
                    ->response()
                    ->success(trans('admin.update_succeeded'))
                    ->redirect('auth/logout');
            });
        });
    }

}
